#!/bin/bash

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
    echo "Illegal number of parameters"
    exit 1
fi

TAG=$1
DRY_RUN=""
[ "$#" -eq 2 ] && DRY_RUN=$2

echo "---- Build Discuz Q Offline Package and Upload to COS -----------------------------"

[ "$DRY_RUN" = "-n" ] && echo "Dry run, no changes will be pushed to remote"

# dzq vendor代码仓库
DZQ_VENDOR_REPO="git@gitee.com:kotlindev/dzq_vendor.git"

BASE="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd $BASE

function check_discuz() {
    cd $BASE
    if [ -d dz_temp ]; then
        echo "---- dz_temp exists"
    else
        ./build_discuz $TAG -n
    fi
}

function check_framework() {
    cd $BASE
    if [ -d framework_temp ]; then
        echo "---- framework_temp exists"
    else
        ./build_framework $TAG -n
    fi
}

function fix_git() {
    cd $BASE/framework_temp
    echo "---- removing framework git repo"
    rm -rf .git .github
    echo "---- removing discuz git repo"
    cd $BASE/dz_temp
    rm -rf .git .github
}

function rename_discuz() {
    cd $BASE
    echo ---- rename dz_temp to dzfull_temp
    rm -rf dzfull_temp
    mv dz_temp dzfull_temp
}

function fix_composer() {
    cd $BASE/dzfull_temp
    echo "---- fixing composer.json"
    cat composer.json | jq ".require.\"discuz/core\" = \"dev-master\"" | jq '.repositories = [{ "type": "path", "url": "./framework" }]' >composer-fixed.json
    mv composer-fixed.json composer.json
}

function merge_framework_to_dz() {
    cd $BASE
    mv framework_temp dzfull_temp/framework
}

function composer_install() {
    cd $BASE/dzfull_temp
    echo "---- doing composer install"
    docker run --rm -it -v $PWD:/app webdevops/php-nginx:7.4 /bin/bash -c "cd /app && composer config -g repos.packagist composer https://mirrors.tencent.com/composer/ && composer install"
    if [ ! $? -eq 0 ]; then
        echo "composer install failed"
        exit 1
    fi
}


function move_framework_to_vendor() {
    cd $BASE/dzfull_temp
    echo "---- moving framework to vendor/discuz/core"
    rm -rf vendor/discuz/core
    mv framework vendor/discuz/core
}

function clone_vendor() {
    cd $BASE/dzfull_temp
    echo "---- remove vendor"
    rm -rf vendor

    echo "---- clone discuz vendor"
    git clone $DZQ_VENDOR_REPO vendor

    cd $BASE/dzfull_temp/vendor
    git checkout -b br_$TAG $TAG

    rm -rf .git .github
}

function cleanup_vendor() {
    cd $BASE/dzfull_temp
    echo "---- cleaning up vendor"
    rm -rf vendor/endroid/qr-code/assets/fonts/noto_sans.otf
    rm -rf vendor/tencentcloud/tencentcloud-sdk-php/CHANGELOG.md
    rm -rf vendor/tencentcloud/tencentcloud-sdk-php/examples

    mapfile -t dirs_to_keep < <(find . -path ./vendor -prune -false -o -name "*.php" | xargs grep 'TencentCloud\\' | perl -ne 'if(m/use TencentCloud\\(.*?)\\/){ print $1 . "\n"; }' | sort | uniq && printf '\0')
    for dir in $(find vendor/tencentcloud/tencentcloud-sdk-php/src/TencentCloud -mindepth 1 -maxdepth 1 -type d); do
        dir_name=$(basename $dir)
        if [[ " ${dirs_to_keep[@]} " =~ " ${dir_name} " ]]; then
            echo keep $dir_name
        else
            rm -rf $dir
        fi
    done
}

function make_zip() {
    cd $BASE/dzfull_temp
    echo "---- making zip"
    zip -q -r dzq_latest_offline.zip composer.lock
    zip -q -r dzq_latest_offline.zip vendor
}

function upload_zip_to_cos() {
    cd $BASE/dzfull_temp
    if [ ! "$DRY_RUN" = "-n" ]; then
        echo "---- uploading to cos"
        coscmd upload dzq_latest_offline.zip /offline/$TAG.zip
        coscmd upload dzq_latest_offline.zip /dzq_latest_offline.zip

        echo "---- removing zip"
        rm -f dzq_latest_offline.zip
    else
        echo "---- Dry run mode, do not actually upload to cos"
    fi
}

function make_full_install_pack() {
    cd $BASE/dzfull_temp
    rm -f ../dzq_latest_install.zip
    echo "creating dzq full installation pack"
    touch .dzq-full-install-pack
    curl https://discuzq-docs-1258344699.cos.ap-guangzhou.myqcloud.com/dl.php -o public/dl.php
    echo "making dzq full installation zip"
    zip -q -r ../dzq_latest_install.zip .
    rm -f .dzq-full-install-pack
    rm -f public/dl.php
}

function upload_full_zip_to_cos() {
    cd $BASE
    if [ ! "$DRY_RUN" = "-n" ]; then
        echo "---- uploading full zip to cos"
        coscmd upload dzq_latest_install.zip /offline/install_$TAG.zip
        coscmd upload dzq_latest_install.zip /dzq_latest_install.zip

        # echo "---- refreshing cdn" 暂时注释掉刷新cdn
        # tccli cdn PurgePathCache --Paths '["https://dl.discuz.chat"]' --FlushType flush
        echo "---- removing zip"
        rm -f dzq_latest_install.zip
    else
        echo "---- Dry run mode, do not actually upload to cos"
    fi
}

function wait_for_mysqld() {
    docker exec -e MYSQL_PWD=root dzq-mysql mysqladmin ping -h 127.0.0.1 -u root --silent >/dev/null 2>&1
    if [ ! "$?" == "0" ]; then
        echo "not ready, wait 2 more seconds..."
        sleep 2
        wait_for_mysqld
    else
        echo "mysqld started."
    fi
}

function stop_dzq_docker() {
    echo "killing dzq docker ..."
    ds=$(docker ps -a | grep dzq | awk '{print $1}')

    if [ -n "$ds" ]; then
        echo $ds | xargs docker rm -f
    fi
}

function start_dzq_docker() {
    cd $BASE

    stop_dzq_docker

    echo "starting php"
    docker run -d \
        --name dzq-php \
        -p 80:80 -p 3306:3306 \
        -v $PWD/dzfull_temp:/app \
        -v $PWD/nginx/dzq-nginx.conf:/opt/docker/etc/nginx/vhost.conf \
        webdevops/php-nginx-dev:7.4

    docker exec dzq-php chown -R application:application /app

    echo "starting mysql"
    docker run -d \
        --name dzq-mysql \
        --network=container:dzq-php \
        -e MYSQL_ROOT_PASSWORD=root \
        mysql:5.7

    sleep 8
    wait_for_mysqld

    echo "dzq start complete"
}

function install_dzq() {
    cd $BASE
    rm -f dzfull_temp/config/config.php
    rm -f dzfull_temp/storage/install.lock

    echo "init dzq"
    res=$(curl --request POST "http://127.0.0.1/install" \
        --header "Content-Type: application/x-www-form-urlencoded" \
        --data-urlencode "forumTitle=dzqtitle" \
        --data-urlencode "mysqlHost=127.0.0.1" \
        --data-urlencode "mysqlDatabase=dzqdatabase_placeholder" \
        --data-urlencode "mysqlUsername=root" \
        --data-urlencode "mysqlPassword=root" \
        --data-urlencode "tablePrefix=ppre_" \
        --data-urlencode "adminUsername=adminuser" \
        --data-urlencode "adminPassword=admin" \
        --data-urlencode "adminPasswordConfirmation=admin")

    # 正常初始化完成，会返回一个带token的json
    echo $res | jq -e '.token'

    if [ ! "$?" == "0" ]; then
        echo
        echo "dzq init failed"
        echo $res
        exit 1
    fi

    echo "dzq init complete"
}

function export_database() {
    cd $BASE
    echo "export dzq database scheme"
    docker exec -e MYSQL_PWD=root dzq-mysql mysqldump --databases dzqdatabase_placeholder --default-character-set=utf8mb4 -uroot >dzfull_temp/database/init_mysql.sql
}

function cleanup_dzq() {
    stop_dzq_docker
    cd $BASE/dzfull_temp
    rm -f config/config.php
    rm -f storage/install.lock
    rm -f storage/cert/*.key
    rm -f storage/views/*.php
    rm -f public/storage
    rm -f public/.oldversion
}

if [ -f dzfull_temp/.build_complete ]; then
    echo "previous complete build exists, skip building process"
else
    check_discuz
    check_framework
    fix_git
    rename_discuz

    merge_framework_to_dz

    clone_vendor
    cleanup_vendor
    move_framework_to_vendor
fi

start_dzq_docker
install_dzq
export_database
cleanup_dzq

make_zip
upload_zip_to_cos

make_full_install_pack
upload_full_zip_to_cos
